package com.zenglx.multilanguage.util;

import com.zenglx.multilanguage.domain.Language;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 获取用户语言工具类
 * </p>
 *
 * @author liangxi.zeng
 */
@Slf4j
public class LanguageHelper {
    private static volatile String defaultLanguage = "en_US";

    private static final List<Language> LANGUAGES;

    private LanguageHelper() {
    }

    static {
        LANGUAGES = new LinkedList<>();
        LANGUAGES.add(new Language().setCode("zh_CN").setName("简体中文").setDescription("中文(简体)"));
        LANGUAGES.add(new Language().setCode("en_US").setName("English").setDescription("英文(美式)"));
    }

    /**
     * 获取所有的语言
     *
     * @return 语言列表
     */
    public static List<Language> languages() {
        return LANGUAGES;
    }


    /**
     * 根据当前登陆用户获取语言信息
     *
     * @return String
     */
    public static String language() {
        String language = null;
        try {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(Objects.nonNull(attributes)) {
                    HttpServletRequest request = attributes.getRequest();
                    String lang = request.getHeader("x_lang");
                    return StringUtils.hasText(lang)?lang:defaultLanguage;
                }
        } catch (Exception e) {
            log.error("获取多语言异常,异常吞并",e);
            language = defaultLanguage;
        }
        return language;
    }
}
